<?php

namespace app\admin\controller\yexam;

//======= 用户服务

use app\admin\model\yexam\ComboList;
use app\admin\model\yexam\SubjectCombo;
use app\admin\model\yexam\UserCombo;
use app\common\controller\Backend;
use app\common\library\Token;
use app\common\model\Category;
use app\common\model\User;
use fast\Random;
use think\Db;
use think\Exception;
use think\Hook;

class UserService extends Backend
{
    protected static $instance = null;
    protected $_logined = false;
    protected $_user = null;
    protected $_token = '';
    //Token默认有效时长
    protected $keeptime = 2592000;
    protected $rules = [];
    //默认配置
    protected $config = [];
    protected $options = [];
    //==== 套餐开通
    public function combo_open(){
        return $this->fetch();
    }
    /**
     * @ApiTitle (获取套餐列表)
     * @ApiParams (name=subject_id)
     */
    public function getComboList(){
        $subjectId = $this->request->param('subject_id',0);
        if ($subjectId == 0) $this->error('科目id错误');
        $combo = new \app\admin\model\yexam\SubjectCombo();
        $this->success('ok','',$combo->where('subject_id',$subjectId)->select());
    }
    //=========== 请求开通套餐
    public function requestOpenCombo(){
        $mobile = $this->request->post('mobile');
        $subjectId = $this->request->post('subject_id',0);
        $comboId = $this->request->post('combo_id',0);
        $remark = $this->request->post("remark",'');
        $user = new User();
        $user = $user->where('mobile',$mobile)->find();
        //  账号，如果有就对账号进行科目套餐开通，如果没有账号则注册账号且开通科目套餐，默认密码123456
        if (strlen($mobile) != 11) $this->error('手机号不正确');
        if ($comboId == 0) $this->error("套餐不正确");
        if ($subjectId == 0) $this->error('科目不正确');
        if (is_null($user)){  //====注册账号
            if ($this->registerUserAndOpemCombo($mobile,$subjectId,$comboId))
                $this->success('开通成功');
            else
                $this->success('开通失败');
        }else{  //==== 开通套餐
            $comboSubject = SubjectCombo::get([
                'subject_id' => $subjectId,
                'combo_id' => $comboId
            ]);
            $comboInfo = ComboList::get(['id' => $comboId]);
            if ($comboSubject && $comboInfo) {
                $userCombo = new UserCombo();
                $hasCombo = $userCombo->where("user_id",$user->id)->where('subject_id',$subjectId)->where('pay_comboid',$comboId)->find();
                if ($comboInfo['combo_type'] != 1){ //=== 考季
                    $catId = $comboInfo->category_id;
                    $category = \app\admin\model\yexam\ComboCategory::get($catId);
                    $invalidTime = strtotime($category->exam_time) + 365*24*60*60;//在考季的基础上续费1年
                }else{// 年限
                    $invalidTime = strtotime("+{$comboInfo->combo_time}year");
                }
                if ($hasCombo){ //==== 已经购买了套餐
                    if ($hasCombo->invalid_time < time()){ //=== 套餐已经过期
                        if ($comboInfo['combo_type'] == 1){ //=== 年限
                            $hasCombo->invalid_time = $invalidTime;
                        }else{
                            $hasCombo->invalid_time = $invalidTime;
                        }
                    }else{ //=== 套餐未过期，再原过期时间上增加1年
                        $hasCombo->invalid_time = strtotime($hasCombo->invalid_time) + 365*24*60*60;
                    }
                    $hasCombo->remark = $remark;
                    $hasCombo->save();
                }else{ //=== 未购买过套餐
                    $userCombo->user_id = $user->id;
                    $userCombo->subject_id = $subjectId;
                    $userCombo->invalid_time = $invalidTime;
                    $userCombo->pay_comboid = $comboId;
                    $userCombo->pay_time = time();
                    $userCombo->remark = $remark;
                    $userCombo->save();
                }
            }
            $this->success('开通成功');
        }
    }
    //====== 用户查询
    public function user_select(){
        return $this->fetch();
    }
    //=== 显示开通列表
    public function index(){
        $userCombo = new UserCombo();
        list($where,$sort,$order,$offset,$limit,$page) = $this->buildparams();
        $search = $this->request->param('search');
        if (!empty($search)){
            $search = $this->request->param('search');
            $allCombo = $userCombo->field('combo.*,u.username,u.mobile,s.short_name,info.combo_name')->alias('combo')->join('user u','combo.user_id = u.id')
                ->join('yexam_subject s','combo.subject_id = s.id')->join('yexam_combo_list info','info.id = combo.pay_comboid')
                ->whereLike('u.mobile',"%{$search}%")->order($sort,$order)->page($page,$limit)->select();
            $total = count($allCombo);
        }else{
            $allCombo = $userCombo->field('combo.*,u.username,u.mobile,s.short_name,info.combo_name')->alias('combo')->join('user u','combo.user_id = u.id')
                ->join('yexam_subject s','combo.subject_id = s.id')->join('yexam_combo_list info','info.id = combo.pay_comboid')
                ->order($sort,$order)->page($page,$limit)->select();
            $total = $userCombo->count();
        }
        return json([
            'rows' => $allCombo,
            'total' => $total
        ]);
    }
    //==== 用户注册并开通
    private function registerUserAndOpemCombo($mobile,$subjectId,$comboId,$password="123456",$email="",$extend=[]){
        $subject = \app\admin\model\yexam\Subject::get($subjectId);
        $extend['entry_platform'] = 'pc';
        $extend['url_source'] = '后台注册';
        $extend['class_name'] = $subject->en_name;
        $extend['class_title'] = $subject->short_name; //=== 科目简称
        $username = $mobile;
        $ip = request()->ip();
        $time = time();
        $data = [
            'username' => $username,
            'password' => $password,
            'email'    => $email,
            'mobile'   => $mobile,
            'level'    => 1,
            'score'    => 0,
            'avatar'   => '',
        ];
        $params = array_merge($data, [
            'nickname'  => preg_match("/^1[3-9]{1}\d{9}$/",$username) ? substr_replace($username,'****',3,4) : $username,
//            'salt'      => Random::alnum(),
            'salt'      => '31yROlcjKKeHeLgOao',
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ]);
        $params['password'] = $this->getEncryptPassword($password, $params['salt']);
        $params = array_merge($params, $extend);
        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = User::create($params, true);
            $this->_user = User::get($user->id);
            //设置Token
            $this->_token = Random::uuid();
            Token::set($this->_token, $user->id, $this->keeptime);
            //注册成功的事件
            Hook::listen("user_register_successed", $this->_user, $data);
            //====== 开通套餐
            $comboSubject = SubjectCombo::get([
                'subject_id' => $subjectId,
                'combo_id' => $comboId
            ]);
            $comboInfo = ComboList::get(['id' => $comboId]);
            if ($comboSubject && $comboInfo) {
                if ($comboInfo['combo_type'] == 1){ //== 年限
                    $invalidTime = strtotime("+{$comboInfo->combo_time}year");
                }else{ //== 考试季
                    $catId = $comboInfo->category_id;
                    $category = \app\admin\model\yexam\ComboCategory::get($catId);
                    $invalidTime = strtotime($category->exam_time);
                }
                $userCombo = new UserCombo();
                $hasCombo = $userCombo->where("user_id",$user->id)->where('subject_id',$subjectId)->where('pay_comboid',$comboId)->find();
                if ($hasCombo){
                    $hasCombo->invalid_time = strtotime($hasCombo->invalid_time) + $invalidTime;
                    $hasCombo->save();
                }else{
                    $userCombo->user_id = $user->id;
                    $userCombo->subject_id = $subjectId;
                    $userCombo->invalid_time = $invalidTime;
                    $userCombo->pay_comboid = $comboId;
                    $userCombo->pay_time = time();
                    $userCombo->save();
                }
            }else{
                Db::rollback();
                return false;
            }
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        return true;
    }
    /**
     * 获取密码加密后的字符串
     * @param string $password 密码
     * @param string $salt     密码盐
     * @return string
     */
    public function getEncryptPassword($password, $salt = '')
    {
//        return md5(md5($password) . $salt);
        return md5(md5($salt.$password));
    }
    //===== 查询是否已经开通了套餐，如果开通了套餐则显示开通的对应套餐
    public function getUserComboInfo(){
        $mobile = $this->request->param('mobile',0);
        if ($mobile == 0) $this->error('请填写手机号');
        $user = User::get(['mobile' => $mobile]);
        if (is_null($user)){
            $this->error('用户不存在','',-1);
        }
        $userCombo = new UserCombo();
        $result = $userCombo->where('user_id',$user['id'])->alias("b.combo_name")->alias("a")
            ->join("yexam_combo_list b",'a.pay_comboid=b.id','left')->select();
        if (count($result) == 0)
            $this->error('未开通','',-2);
        $str = "";
        foreach ($result as $value){
            $str .= "<p>【{$value['combo_name']}】</p>";
        }
        $this->success('请求成功','',$str);
    }
    //========= 备注编辑
    public function edit($ids=null){
        $userCombo = UserCombo::get($ids);
        $row = $this->request->param('row/a');
        $userCombo->remark = $row['remark'];
        $userCombo->save();
        $this->success('保存成功');
    }
}